package avicit.im.lantop.basic.reportmanager.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fr.data.impl.Connection;
import com.fr.data.impl.DBTableData;
import com.fr.data.impl.EmbeddedTableData;
import com.fr.file.DatasourceManager;
import com.fr.main.impl.WorkBook;
import com.fr.report.worksheet.WorkSheet;

/**
 * <p>金航数码科技有限责任公司</p>
 * <p>作者：张欢欢</p>
 * <p>邮箱：xtcqw369@163.com</p>
 * <p>创建时间： 2015-11-3 下午1:56:47 </p>
 * <p>类说明：帆软报表cpt模板生成工具类</p>
 * <p>修改记录： </p>
 */
public class CreateCPT {

	private List<String> columnList = null;
	private String sql = null;
	private String path = null;
	private String connName = null;
	private WorkBook workbook = null;
	private String defaultDir = "reportlets";
	private String fileExt = ".cpt";

	private static final Logger LOGGER = LoggerFactory.getLogger(CreateCPT.class);

	public CreateCPT(List<String> columnList, String sql, String path, String connName) {
		this.columnList = columnList;
		this.sql = sql;
		this.path = path + File.separator + defaultDir;
		this.connName = connName;
		init();

	}
	
	/**
	 * TODO 初始化方法
	 *  void
	 * @throws
	 */
	private void init() {

		workbook = new WorkBook();
		WorkSheet sheet1 = new WorkSheet();
		DBTableData ds1 = new DBTableData();
		DatasourceManager datasourceManager = DatasourceManager.getInstance();
		// 通过数据源连接名，选择数据源连接
		Connection dbconnection = datasourceManager.getConnection(connName);
		ds1.setDatabase(dbconnection);
		ds1.setQuery(sql);
		// sheet1.setCellValue(0, 0, "TEST"); // 向单元格中写入数据
		// 设置数据集的名字
		workbook.putTableData("data", ds1);

		EmbeddedTableData etd = new EmbeddedTableData();
		for (String column : columnList) {
			etd.addColumn(column, String.class);
		}

		etd.addRow(columnList);

		workbook.putTableData("数据源", etd);

		workbook.addReport(sheet1);

	}
	
	/**
	 * TODO 将cpt模板文件保存到WEB-INF目录下
	 * @param fileName
	 * @return boolean
	 * @throws
	 */
	public boolean saveCPT(String fileName) {

		boolean success = false;

		fileName = this.path + File.separator + fileName + fileExt;

		File cptFile = new File(fileName);

		OutputStream fo = null;

		try {
			fo = new FileOutputStream(cptFile);
			workbook.export(fo);
			success = true;
		} catch (FileNotFoundException e2) {
			success = false;
			LOGGER.error("FileNotFound,fileName: " + fileName, e2);

		} catch (Exception e) {
			success = false;
			LOGGER.error("save cpt file error, ", e);

		} finally {
			if (null != fo) {
				try {
					fo.close();

				} catch (IOException e) {
					success = false;
					LOGGER.error("close error: ", e);
				}

			}
		}
		return success;
	}

}
